<?php

namespace App\Http\Controllers\Saas;

use App\Http\Controllers\Controller;
use App\Http\Util\TripleDES;
use App\Service\Baofu;
use App\Utils\Result;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ComplaintController extends Controller
{
    public function list(Request $request)
    {
        try {
            $start = $request->input('start');
            $end = $request->input('end');
            $limit = $request->input('limit', 10);
            $page = $request->input('page', 1);
            $offset = ($page - 1) * $limit;

            $baofu = new Baofu($request);

            // 查询指定时间段的投诉列表
            $result = $baofu->queryComplaintList([
                'beginDate' => $start,
                'endDate' => $end,
                'limit' => $limit,
                'offset' => $offset
            ]);

            return Result::success($result);
        } catch (\Exception $e) {
            return Result::error(1001, '查询投诉列表失败: ' . $e->getMessage());
        }
    }

    public function detail(Request $request)
    {
        try {
            $complaintId = $request->input('complaintId');
            $baofu = new Baofu($request);
            $result = $baofu->queryComplaintDetail($complaintId);
            return Result::success($result);
        } catch (\Exception $e) {
            return Result::error(1002, '查询投诉详情失败: ' . $e->getMessage());
        }
    }

    public function getPhone(Request $request)
    {
        try {
            $key = $request->input('key');
            $phone = $request->input('phone');
            $baofu = new Baofu($request);
            $deskey = $baofu->decrptByPem($key);
            $deskeyde = bin2hex($deskey);
            $desstr['phone'] = TripleDES::decrypt($phone, $deskeyde);
            return Result::success($desstr);
        } catch (\Exception $e) {
            return Result::error(1003, '解密手机号失败: ' . $e->getMessage());
        }
    }

    public function history(Request $request)
    {
        try {
            $complaintId = $request->input('complaintId');
            $limit = $request->input('limit', 10);
            $page = $request->input('page', 1);
            $offset = ($page - 1) * $limit;
            $baofu = new Baofu($request);
            $result = $baofu->queryNegotiationHistory($complaintId, [
                'limit' => $limit,
                'offset' => $offset
            ]);
            return Result::success($result);
        } catch (\Exception $e) {
            return Result::error(1004, '查询协商历史失败: ' . $e->getMessage());
        }
    }

    // 投诉回复接口
    public function handleComplaintReply(Request $request)
    {
        try {
            $baofu = new Baofu($request);

            // 获取请求参数
            $complaintId = $request->input('complaintId');
            $responseContent = $request->input('response_content');
            $images = $request->input('images', []); // 图片ID数组
            $jumpUrl = $request->input('jump_url');
            $jumpUrlText = $request->input('jump_url_text');

            // 构造参数
            $params = [];
            if (!empty($images)) {
                $params['responseImages'] = $images;
            }
            if (!empty($jumpUrl) && !empty($jumpUrlText)) {
                $params['jumpUrl'] = $jumpUrl;
                $params['jumpUrlText'] = $jumpUrlText;
            }

            // 调用回复接口
            $result = $baofu->complaintResponse(
                $complaintId,
                $responseContent,
                $params
            );

            if ($result['resultCode'] === 'SUCCESS') {
                $data = [
                    'status' => 'success',
                    'message' => '回复成功',
                    'data' => $result
                ];
                return Result::success($data);
            } else {
                return Result::error(2001, '回复失败：' . $result['errMsg']);
            }
        } catch (\Exception $e) {
            return Result::error(2002, '操作异常：' . $e->getMessage());
        }
    }

    // 上传图片
    public function uploadImage(Request $request)
    {
        try {
            $baofu = new Baofu($request);

            $complaintId = $request->input('complaintId');
            $image = $request->file('image');

            // 验证文件
            if (!$image || !$image->isValid()) {
                return Result::error(3001, '无效的图片文件');
            }

            // 获取图片数据
            $imageData = file_get_contents($image->getRealPath());
            $fileName = $image->getClientOriginalName();

            // 上传图片
            $result = $baofu->uploadComplaintImageData(
                $complaintId,
                $imageData,
                $fileName
            );

            if ($result['resultCode'] === 'SUCCESS') {
                $data = [
                    'status' => 'success',
                    'message' => '图片上传成功',
                    'data' => [
                        'media_id' => $result['mediaId']
                    ]
                ];
                return Result::success($data);
            } else {
                return Result::error(3002, '图片上传失败：' . $result['errMsg']);
            }
        } catch (\Exception $e) {
            return Result::error(3003, '系统异常：' . $e->getMessage());
        }
    }

    // 投诉处理完成反馈
    public function replayComplete(Request $request)
    {
        try {
            $baofu = new Baofu($request);
            // 获取请求参数
            $complaintId = $request->input('complaintId');
            $complaintedMchid = $request->input('complainted_mchid');
            // 构造参数
            $params = [];
            if (!empty($complaintedMchid)) {
                $params['complaintedMchid'] = $complaintedMchid;
            }

            // 调用反馈处理完成接口
            $result = $baofu->complaintComplete($complaintId, $params);

            if ($result['resultCode'] === 'SUCCESS') {
                $data = [
                    'status' => 'success',
                    'message' => '投诉处理完成反馈成功',
                    'data' => $result
                ];
                return Result::success($data);
            } else {
                return Result::error(4001, '反馈失败：' . $result['errMsg']);
            }
        } catch (\Exception $e) {
            return Result::error(4002, '系统异常：' . $e->getMessage());
        }
    }

    /**
     * 下载图片并保存到本地
     */
    public function downloadImage(Request $request)
    {
//        try {
            $complaintId = $request->input('complaintId');
            $mediaUrl = $request->input('mediaId');
            $savePath = $request->input('savePath');

            if (empty($complaintId)) {
                return Result::error(5001, '投诉单号不能为空');
            }

            if (empty($mediaUrl)) {
                return Result::error(5002, '媒体文件请求url不能为空');
            }

            if (empty($savePath)) {
                return Result::error(5003, '保存路径不能为空');
            }

            $extraParams = [];
            if ($request->has('agent_mer_id')) {
                $extraParams['agentMerId'] = $request->input('agent_mer_id');
                $extraParams['agentTerId'] = $request->input('agent_ter_id');
            }

            $baofu = new Baofu($request);
            // 下载并保存图片
            $result = $baofu->downloadImageToFile($complaintId, $mediaUrl, $savePath, $extraParams);

            if ($result) {
                $data = [
                    'status' => 'success',
                    'message' => '图片获取成功',
                    'data' => $result
                ];
                return Result::success($data);
            } else {
                return Result::error(5004, '图片下载保存失败');
            }
//        } catch (\Exception $e) {
//            return Result::error(5005, '系统异常：' . $e->getMessage().$e->getMessage());
//        }
    }
}
